//
//  SWRevealMenu.swift
//  ChildStory
//
//  Created by linhan on 2016/11/11.
//  Copyright © 2016年 Aiya. All rights reserved.
//

import Foundation
import UIKit

private var _menu:SWRevealMenu = SWRevealMenu()
class SWRevealMenu:NSObject,SWPopupContainerDelegate,SWAPIComponent
{
    var selectedCallback:((Int)->Void)?
    private var _lastIndex = 0
    
    private var _menuView:SWRevealMenuView?
    lazy private var _popupContainer:PopupContainer = PopupContainer()
    
    private var _menus:[SWRevealMenuItem] = []{
        didSet{
            if _menus.count > 0
            {
                _menuView?.menus = _menus
                _menuView?.selectedIndex = 0
            }
        }
    }
    
    class var shared:SWRevealMenu
    {
        return _menu
    }
    
    override init()
    {
        super.init()
        //setup()
    }
    
    func setup()
    {
        loadData()
    }
    
    private func loadData()
    {
        let req = SWStagesFetchReq()
        req.successCallback = {[weak self] response,cache in
            if let response = response as? SWStagesFetchRsp
            {
                let title = response.stages?.flatMap({$0.title ?? ""}) ?? []
                print(title)
                
                let menus = response.stages?.flatMap({SWRevealMenuItem(stage: $0)}) ?? []
                self?._menus = menus
            }
        }
        load(req)
    }
    
    func show()
    {
        if _menuView == nil
        {
            _popupContainer.delegate = self
            
            let screenSize = UIScreen.main.bounds.size
            let menuRect = CGRectMake(0, 0, 225, screenSize.height)
            let menuView = SWRevealMenuView(frame: menuRect)
            menuView.selectedCallback = {[weak self] index in
                self?.munuSelected(index:index)
            }
            
            _menuView = menuView
            
            if _menus.count > 0
            {
                let aMenus = _menus
                _menus = aMenus
            }
        }
        
        if let menuView = _menuView
        {
            _popupContainer.show(menuView)
        }
    }
    
    func close(animated:Bool = true)
    {
        _popupContainer.close(animated)
    }
    
    func willPresentPopupContainer()
    {
        guard let menuView = _menuView else {
            return
        }
        menuView.x = -menuView.width
        UIView.animate(withDuration: 0.2, animations: {
            menuView.alpha = 1
            menuView.x = 0
        })
    }
    
    func willDismissPopupContainer()
    {
        guard let menuView = _menuView else {
            return
        }
        
        UIView.animate(withDuration: 0.2, animations: {
            menuView.alpha = 0
            menuView.x = -menuView.width
        })
    }
    
    private func munuSelected(index:Int)
    {
        close()
        if _lastIndex != index
        {
            _lastIndex = index
            selectedCallback?(index)
        }
    }
    
    
    
    
}

fileprivate struct SWRevealMenuItem
{
    var title:String = ""
    var index:Int = 0
    
    init?(stage:SWStageRsp)
    {
        guard let title = stage.title else{
            return nil
        }
        
        self.title = title
        //self.index = index
    }
}

fileprivate class SWRevealMenuView:UIView,UITableViewDelegate,UITableViewDataSource
{
    var menus:[SWRevealMenuItem] = [] {
        didSet{
            _tableView.reloadData()
            selectedIndex = 0
        }
    }
    
    var selectedIndex:Int = -1 {
        didSet{
            if selectedIndex != oldValue && selectedIndex >= 0 && selectedIndex < menus.count
            {
                //_tableView.reloadRows(at: [IndexPath(row:selectedIndex, section:0)], with: .none)
                _tableView.selectRow(at: IndexPath(row:selectedIndex, section:0), animated: false, scrollPosition: .top)
            }
        }
    }
    
    var selectedCallback:((Int)->Void)?
    
    private var _tableView:UITableView = UITableView()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setup()
    {
        backgroundColor = UIColor.lightGray
        
        let headerView = UIView()
        headerView.backgroundColor = UIColor(hex:0xececec)
        headerView.frame = CGRectMake(0, 0, bounds.width, 64)
        
        let statusView = UIView()
        statusView.backgroundColor = UIColor.white
        statusView.frame = CGRectMake(0, 0, bounds.width, 20)
        headerView.addSubview(statusView)
        
        let sloganView = UIView()
        sloganView.frame = CGRectMake(0, statusView.bottom, bounds.width, 44)
        headerView.addSubview(sloganView)
        
        let sloganLabel:UILabel = UILabel()
        sloganLabel.textColor = UIColor(hex: 0x515151)
        sloganLabel.font = UIFont.systemFont(ofSize: 12)
        sloganLabel.text = "只为宝宝成长"
        sloganLabel.sizeToFit()
        sloganLabel.center = sloganView.bounds.center
        sloganView.addSubview(sloganLabel)
        
        let leftIcon:UIImageView = UIImageView(image: UIImage(named:"main_menu_icon_left"))
        leftIcon.center = CGPointMake(sloganLabel.x - leftIcon.width * 0.5 - 6, sloganLabel.center.y)
        sloganView.addSubview(leftIcon)
        
        let rightIcon:UIImageView = UIImageView(image: UIImage(named:"main_menu_icon_right"))
        rightIcon.center = CGPointMake(sloganLabel.right + rightIcon.width * 0.5 + 6, sloganLabel.center.y)
        sloganView.addSubview(rightIcon)
        
        
        _tableView.frame = bounds
        _tableView.delegate = self
        _tableView.dataSource = self
        _tableView.tableFooterView = UIView()
        _tableView.tableHeaderView = headerView
        _tableView.rowHeight = 62
        _tableView.backgroundColor = UIColor.white
        _tableView.separatorColor = UIColor(hex: 0xc2c2c2)
        addSubview(_tableView)
        _tableView.separatorInset = UIEdgeInsets.zero
        if #available(iOS 8.0, *) {
            _tableView.layoutMargins = UIEdgeInsets.zero
        }
        
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return menus.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        var cell:UITableViewCell?
        if let item = menus.valueAt(indexPath.row)
        {
            let identifier:String = "Cell"
            let selected:Bool = selectedIndex == indexPath.row
            cell = tableView.dequeueReusableCell(withIdentifier: identifier)
            if cell == nil
            {
                cell = SWRevealMenuCell(style: .default, reuseIdentifier: identifier)
                cell?.backgroundColor = UIColor.clear
                cell?.accessoryType = .none
                cell?.textLabel?.font = UIFont.systemFont(ofSize: 14)
                cell?.textLabel?.textColor = UIColor(hex: 0x535353)
                cell?.imageView?.image = UIImage(named: "main_menu_icon_date")
                if #available(iOS 8.0, *) {
                    cell?.layoutMargins = UIEdgeInsets.zero
                }
                else{
                    cell?.separatorInset = UIEdgeInsets.zero
                }
            }
            cell?.setSelected(selected, animated: false)
            cell?.textLabel?.text = item.title
        }
        return cell ?? UITableViewCell()
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
    {
//        tableView.deselectRow(at: indexPath, animated: true)
//        if indexPath.row != selectedIndex
//        {
//            let lastIndex:Int = selectedIndex
//            var indexPaths:[IndexPath] = [indexPath]
//            if lastIndex >= 0 && lastIndex < menus.count
//            {
//                indexPaths.append(IndexPath(row: lastIndex, section: 0))
//            }
//            selectedIndex = indexPath.row
//            tableView.reloadRows(at: indexPaths, with: .none)
//        }
        //_previousRow = indexPath.row
        if indexPath.row != selectedIndex
        {
            selectedIndex = indexPath.row
            selectedCallback?(indexPath.row)
        }
    }
    
    
    
    
    
    
    
    
}

fileprivate class SWRevealMenuCell: UITableViewCell
{
    
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        selectedBackgroundView = UIView()
        selectedBackgroundView?.backgroundColor = UIColor(hex: 0xf5f5f5)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
